<?
/**
 * VoiceOne Settings/MOH
 *
 * Frontend to manage music on hold in voiceone.
 * @package voiceone
 * @subpackage  settings_moh
 */
  include ("../../admin/config/cfg.php");
  global $cwlang;
  
  //=============== POST and GET ===============
  $alert=getAlert();  
  //delete a class
  if(count($_GET)>0){
    if (($_GET["cmd"]=="delclass")&&(isset($_GET["name"]))){
      $ret=$asterisk->delMohClass($_GET["name"]);
      if ($ret==1) $alert="<div class=\"AlertGood\">".$cwlang["moh"]["alertDelClassGood"]."</div>";
      else $alert="<div class=\"AlertBad\">".$cwlang["moh"]["alertDelClassBad"]."</div>";
      goToMainPage($alert,"./");
    }   
  }
  else if(count($_FILES)>0){
    // File upload check
    if (!is_uploaded_file($_FILES['uploadedfile']['tmp_name'])) {
      if($_FILES['uploadedfile']['error']==1) $alert="<div class=\"AlertBad\">".$cwlang["moh"]["alertUpErr1Bad"]."</div>";
      else if($_FILES['uploadedfile']['error']==2) $alert="<div class=\"AlertBad\">".$cwlang["moh"]["alertUpErr2Bad"]."</div>";
      else $alert="<div class=\"AlertBad\">".$cwlang["moh"]["alertUploadBad"]."</div>";
      unlink($_FILES['uploadedfile']['tmp_name']);  
      goToMainPage($alert,"./");
    } 
    else { // File correctly uploaded
      $songsList=$asterisk->getMohSongs("");
      $file_name=$_FILES['uploadedfile']['name'];
      $new_file_name=$file_name;
      error_log("Temporary file name: $file_name");
      $go=false;
      $count=2;
      while($go!==true){
        $go=true;
        foreach($songsList as $song){
          $song=substr($song, 0, -1);
          if($song==$new_file_name) {
            $new_file_name=$count."_".$file_name;
            $go=false;
            break;   
          }    
        }
        $count++;
      }
      $handle = fopen($_FILES['uploadedfile']['tmp_name'],"rb");
      $file_content = fread($handle,filesize($_FILES['uploadedfile']['tmp_name']));
      $ret=$asterisk->uploadMohSongs($new_file_name, $file_content);
      if ($ret>0) {$alert="<div class=\"AlertGood\">".$cwlang["moh"]["alertUploadGood"]."</div>";
      } else $alert="<div class=\"AlertBad\">".$cwlang["moh"]["alertUploadBad"]."</div>";
      goToMainPage($alert,"./");
    }
  }
  else if(count($_POST)>0){
    //delete a songs list
    if(($_POST["cmd"]=="delsong")&&(is_array($_POST["songsList"]))){
      if(count($_POST["songsList"])==0) goToMainPage("", "./");
      else {
        foreach($_POST["songsList"] as $song){
          $ret=$asterisk->deleteMohSong($song);
          if($ret==0){
            $alert="<div class=\"AlertBad\">".$cwlang["moh"]["alertDelSongBad"]."</div>";
            goToMainPage($alert,"./");
          }
        }
        $alert="<div class=\"AlertGood\">".$cwlang["moh"]["alertDelSongGood"]."</div>";
        goToMainPage($alert,"./");
      }
    }
  }
  //================ PAGE LOGIC ================
  //create a visual list of classes
  $ret=$asterisk->getMohClass("");
  $count=1;
  if (is_array($ret)){
    foreach($ret as $class){
      $id=$class["id"];
      $name=$class["name"];
      if($name=="default") $html_def.="<td><img src=\"$relBasePath/public/img/music_note.gif\" />$prot <a href=\"edit/?name=$name\">$name</a></td>\n";
      else {
        $html.="<td><img src=\"$relBasePath/public/img/music_note.gif\" />$prot <a href=\"edit/?name=$name\">$name</a> <a href=\"$PHP_SELF?cmd=delclass&name=$name\" onclick=\"if (confirm('".$cwlang["moh"]["confirmDel"]." $name?')) return true; else return false;\"><img src=\"$relBasePath/public/img/trash.gif\" /></a></td>\n";
        if((++$count)%2==0) $html.="</tr><tr>\n";  
      }
    }
  }
  $html=$html_def.$html;
  //create a visual list of songs
  $ret=$asterisk->getMohSongs("");
  if(is_array($ret))
  foreach($ret as $song){
    $songsList.="<option value=\"$song\" >$song</option>";  
  }
  //set upload limit
  function return_bytes($val) {
    $val = trim($val);
    $last = $val{strlen($val)-1};
    switch($last) {
      case 'k':
      case 'K':
        return (int) $val * 1024;
        break;
      case 'm':
      case 'M':
        return (int) $val * 1048576;
        break;
      default:
        return $val;
    }
  }
  $uploadlimit=min(return_bytes(ini_get("post_max_size")),return_bytes(ini_get("upload_max_filesize")));
    
  //================ MAIN CONTENTS ================
  ob_start();
  ?>
    <div class="SectionHeader">
      <?=$alert?>
      <h1><?=$cwlang["moh"]["title"]?></h1>
      <h3>
        <a href="edit/" class="admin" ><?=$cwlang["moh"]["newClass"]?></a> 
      </h3>
    </div>
    <table class="todolist">
      <tr>
        <?=$html?>
      </tr>
    </table>
  <?
  $contents=ob_get_contents();
  ob_end_clean();

  //================ SIDEBAR ================
  ob_start(); 
  ?>
    <div class="Sidebar">
      <h1><?=$cwlang["moh"]["sidebarTitle"]?></h1>
          <?=$cwlang["moh"]["sidebarDesc"]?>
    </div>
    <!-- Upload audio files --> 
    <div id="basic_form">
      <div class="block">

        <form action="<?=$PHP_SELF?>" method="post" enctype="multipart/form-data">
          <input type="hidden" name="MAX_FILE_SIZE" value="<?=$uploadlimit?>">          
          <table >
            <tr><td colspan="2"><?=$cwlang["moh"]["FileUpload"]?>:</td></tr>
            <tr>
              <td><input type="file" id="uploadedfile" name="uploadedfile" size="14" value="" /></td>
              <td><input type="image" src="<?=$relBasePath?>/public/img/add.gif" alt="Upload" onclick="return checkUpload()" /></td>  
            </tr>
          </table>
        </form>

        <hr/>
        <form action="<?=$PHP_SELF?>" method="post">
          <input type="hidden" name="cmd" value="delsong">
          <table>
            <tr><td colspan="2"><?=$cwlang["moh"]["FileLib"]?>:</td></tr>
            <tr>
              <td style="width: 100%"><select multiple style="width: 100%" size="10"  name="songsList[]" id="songsList"><?=$songsList?></select></td>
              <td><input type="image" src="<?=$relBasePath?>/public/img/trash.gif" alt="Upload" onclick="if (confirm('<?=$cwlang["moh"]["AlertDelFile"]?>?')) return true; else return false;"></td>
            </tr>
          </table>  
        </form>
      </div> 
    </div>

  <script>
  function checkUpload(){
    var filename = document.getElementById("uploadedfile").value;
    if(filename==""){
      alert('Please insert filepath first');
      return false;
    }
    else return true
  }
  </script>
        
     
  <?  
  $sidebar=ob_get_contents();
  ob_end_clean();

  //================ SETTINGS ================
  $smarty->assign("section", "moh");
  $smarty->assign("subsection", "");
  $smarty->assign("templateType", "TwoColLeft");  //OneCol, TwoColLeft, TwoColRight
  $smarty->assign("contents", $contents);
  $smarty->assign("sidebar", $sidebar);
  $smarty->display('settings.tpl');
?>